package com.party.web.biz.system.member;

import com.google.common.collect.Lists;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.PinyinUtil;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.circle.Circle;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.system.*;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.circle.CircleBizNewService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.photo.AlbumBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName MemberGroupBizService
 * @Description TODO
 * @Author yifeng
 * @Date 2019/9/26 16:05
 **/
@Service
public class MemberGroupBizService {
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private CircleBizService circleBizService;
    @Autowired
    private CircleBizNewService circleBizNewService;
    @Autowired
    private IPhotoProjectService photoProjectService;
    @Autowired
    private AlbumBizService albumBizService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private FileBizService fileBizService;

    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 保存机构信息
     *
     * @param member
     * @return
     * @author yifeng
     * @date 16:09 2019/9/26
     **/
    public void savePartnerBiz(MemberGroup member) throws Exception {
        if (StringUtils.isNotEmpty(member.getId())) {
            // 从数据库取出记录的值
            MemberGroup t = memberGroupService.get(member.getId());

            // 将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(member, t);

            String realname = t.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroupService.update(t);

            memberSetService.initMemberSet(member.getId());

            CurrentUser newCurrentUser = RealmUtils.getNewCurrentUser();
            if (member.getId().equals(newCurrentUser.getId())) {
                com.party.core.utils.MyBeanUtils.copyBeanNotNull2Bean(t, newCurrentUser);
                RealmUtils.getSession().setAttribute(Constant.CURRENT_USER_KEY, newCurrentUser);
            }
        } else {
            // 新增
            String realname = member.getRealname();
            if (StringUtils.isNotBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                member.setRealname(realname);
                member.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            member.setDeployType(0);
            member.setType(Constant.MEMBER_ORGANIZATION);
            member.setIsPartner(YesNoStatus.YES.getCode());

            memberGroupService.insert(member);

            List<SysRole> sysRoles = Lists.newArrayList();
            String systemRole = "";

            if (member.getIsPartner() != null && member.getIsPartner() == 1) {
                systemRole = RoleEnum.PARTNER_ROLE.getCode();
                SysRole sysRole = sysRoleService.getRole(systemRole, RoleType.SYSTEM_ROLE.getCode());
                sysRoles.add(sysRole);
            }

            String partnerId = member.getPartnerId();

            String xzgsMemberId = getXzgsMemberId();
            if (xzgsMemberId.equals(partnerId)) {
                SysRole sysRole = sysRoleService.getRole("oneLevelChild", RoleType.SYSTEM_ROLE.getCode());
                sysRoles.add(sysRole);
            }
            for (SysRole sysRole : sysRoles) {
                MemberSysRole memberSysRole = memberSysRoleService.findByMemberAndRole(member.getId(), sysRole.getId());
                if (null == memberSysRole) {
                    memberSysRole = new MemberSysRole();
                    memberSysRole.setMemberId(member.getId());
                    memberSysRole.setRoleId(sysRole.getId());
                    memberSysRoleService.insert(memberSysRole);
                }
            }
        }
    }

    public void initCricleAndPhoto(MemberGroup member) {
        logger.info("开始初始化圈子.....");
        //创建圈子
        createCircle(member.getId(),member.getRealname());
    }


    private void createCircle(String partnerId,String realName) {

        String name = "行知公社—"+realName+"会员通讯录";
        String memo = "在这里记录健康，记录和行知一起走过的美好时光。";
        String logo = "http://txzapp-10052192.image.myqcloud.com/c94e89415d7d4611b706cecfc43af2ae/image/1574995246561.png";
        String remarks = "时光流逝留下最美好的痕迹。不需要证明这个世界我们曾经来过，" +
                "只要我们一起奋斗过、相互温暖过、共同成长过就无怨无悔。这是行知家人们共同的回忆。";
        Circle circle = new Circle();
        circle.setCreateBy(partnerId);
        circle.setName(name);
        circle.setMemo(memo);
        circle.setLogo(logo);
        circle.setArea("234");
        circle.setShowFront(Integer.valueOf(0));
        circle.setIsOpen(Integer.valueOf(0));
        circle.setIsViewPosition(Integer.valueOf(1));
        circle.setIsChooseGroupp(Integer.valueOf(1));
        circle.setRemarks(remarks);

        logger.info("创建圈子....");
        String circleId = circleBizService.createCircleBiz(circle, partnerId);
        circleBizNewService.uploadQrCode(partnerId, circleId);

        //创建相册
        logger.info("初始相册....");

        createPhoto(circle,realName);


    }
    private void createPhoto(Circle circle,String realName) {
        String name = "行知公社—"+realName+"CEO户外行活动相册";
        PhotoProject photoProject = new PhotoProject();
        photoProject.setMemberId(circle.getCreateBy());
        photoProject.setCircleId(circle.getId());
        photoProject.setName(name);
        photoProject.setOperatePermission(1);
        if(circle.getMemo() != null ) {
            photoProject.setIntroduction(circle.getMemo());
        }
        if(circle.getLogo() != null ) {
            photoProject.setPic(circle.getLogo());
        }
        logger.info("创建相册.....");
        List<PhotoProject> photosList =  photoProjectService.list(photoProject);
        if (photosList.size() == 0) {
            logger.info("创建相册.....");
            photoProjectService.insert(photoProject);
            // 初始化系统标签
            albumBizService.initTags(photoProject.getId());
        } else {
            PhotoProject oldPhotoProject = photosList.get(0);
            oldPhotoProject.setName(circle.getName());
            oldPhotoProject.setPic(circle.getLogo());
            if(circle.getMemo() != null ) {
                oldPhotoProject.setIntroduction(circle.getMemo());
            }
            logger.info("更新相册.....");
            photoProjectService.update(oldPhotoProject);
        }
        try {
            logger.info("获取相册小程序配置参数");
            WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage("pages/photo/index");
            qrCodeRequest.setScene(photoProject.getId());
            String filePath = fileBizService.getUploadCIPath(circle.getCreateBy(), "photo");
            logger.info("上传相册小程序二维码.....");
            fileBizService.uploadCloudOut(photoProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
        } catch (Exception e) {
            logger.error("生成小程序码异常", e);
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveThirdMember() throws Exception {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole("", "third_member_manager"));
        if (sysRole == null) {
            sysRole = new SysRole();
            sysRole.setType(2);
            sysRole.setCode("third_member_manager");
            sysRole.setName("第三方用户");
            sysRole.setDelFlag("1");
            sysRoleService.insert(sysRole);
        }
        MemberGroup thirdMemberManage = memberGroupService.getThirdMemberManage();
        if (thirdMemberManage == null) {
            thirdMemberManage = new MemberGroup();
            thirdMemberManage.setUsername("thirdMemberManage");
            thirdMemberManage.setRealname("第三方用户管理员");
            thirdMemberManage.setDelFlag("1"); // 不显示在列表
            thirdMemberManage.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            thirdMemberManage.setType(Constant.MEMBER_ORGANIZATION);
            // 合作商
            thirdMemberManage.setIsPartner(YesNoStatus.NO.getCode());
            // 管理员
            thirdMemberManage.setIsAdmin(YesNoStatus.NO.getCode());
            // 合作渠道
            thirdMemberManage.setIsCosponsor(YesNoStatus.NO.getCode());
            memberGroupService.insert(thirdMemberManage);
        }

        boolean result = sysRoleService.hasRole(thirdMemberManage.getId(), sysRole.getCode());
        if (!result) {
            MemberSysRole memberSysRole = new MemberSysRole(thirdMemberManage.getId(), sysRole.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    /**
    * @Description: 行知公社管理员保存
    * @Param:
    * @return:
    * @Author: Hua Qunhao
    * @Date: 2020/1/8
    */
    public void saveAdminBiz(MemberGroup memberGroup) {
        if (StringUtils.isEmpty(memberGroup.getId())) {
            String realname = memberGroup.getRealname();
            if (StringUtils.isNotBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                memberGroup.setRealname(realname);
                memberGroup.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroup.setPartnerId(this.getXzgsMemberId());
            memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            memberGroup.setType(Constant.MEMBER_XZGSADMIN);
            memberGroupService.insert(memberGroup);

            SysRole xzgsAdmin = sysRoleService.getRole("xzgsAdmin", RoleType.KNOWLEDGE_MANAGEMENT_ROLE.getCode());
            if (xzgsAdmin != null) {
                MemberSysRole memberSysRole =
                        memberSysRoleService.findByMemberAndRole(memberGroup.getId(), xzgsAdmin.getId());
                if (null == memberSysRole) {
                    memberSysRole = new MemberSysRole();
                    memberSysRole.setMemberId(memberGroup.getId());
                    memberSysRole.setRoleId(xzgsAdmin.getId());
                    memberSysRoleService.insert(memberSysRole);
                }
            }
        } else {
            MemberGroup t = memberGroupService.get(memberGroup.getId());
            try {
                MyBeanUtils.copyBeanNotNull2Bean(memberGroup, t);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String realname = t.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroupService.update(t);
        }
    }
    /**
     * 根据手机号生成合作渠道用户
     *
     * @param mobile      手机号
     * @param countryCode 区号
     * @return 用户id
     */
    public String saveCosponsorMember(String mobile, String countryCode) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        MemberGroup member = new MemberGroup();
        member.setMobile(mobile);
        member.setCountryCode(countryCode);
        member.setIsCosponsor(YesNoStatus.YES.getCode());
        member.setIsAdmin(YesNoStatus.NO.getCode());
        member.setIsPartner(YesNoStatus.NO.getCode());
        member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        member.setType(Constant.MEMBER_ORGANIZATION);
        memberGroupService.insert(member);

        MemberSysRole memberSysRole = new MemberSysRole();
        memberSysRole.setMemberId(member.getId());
        memberSysRole.setRoleId(sysRole.getId());
        memberSysRoleService.insert(memberSysRole);
        return member.getId();
    }

    /**
     * 绑定合作渠道角色
     *
     * @param member 用户
     */
    public void bindCosponsorRole(MemberGroup member) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        if (!YesNoStatus.YES.getCode().equals(member.getIsCosponsor())) {
            member.setIsCosponsor(YesNoStatus.YES.getCode());
            memberGroupService.update(member);
        }

        boolean hasRole = sysRoleService.hasRole(member.getId(), sysRole.getCode());
        if (!hasRole) {
            MemberSysRole memberSysRole = new MemberSysRole();
            memberSysRole.setMemberId(member.getId());
            memberSysRole.setRoleId(sysRole.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    /**
     * 保存用户业务数据____注册
     *
     * @param memberGroup 会员信息
     * @return 会员信息
     * @throws Exception 异常信息
     */
    public MemberGroup saveOrupdatePartnerMember(MemberGroup memberGroup) throws Exception {

        if (StringUtils.isEmpty(memberGroup.getId())) {
            memberGroup.setLogo("http://txzapp-10052192.image.myqcloud.com/1490783498894");
            memberGroup.setRealname(memberGroup.getUsername());
            memberGroup.setPassword(memberGroup.getPassword());
            memberGroup.setIsPartner(YesNoStatus.YES.getCode());
            memberGroup.setType(Constant.MEMBER_ORGANIZATION);
            memberGroup.setIsAdmin(YesNoStatus.NO.getCode());
            memberGroup.setIsCosponsor(YesNoStatus.NO.getCode());
            memberGroup.setDeployType(0);
            memberGroup.setIsHidden(2);
            memberGroup.setTechnicalSupport("我也要使用众筹系统");
            memberGroup.setIsHiddenCopyright(2);

            // 保存
            String memberId = memberGroupService.insert(memberGroup);

            //分配系统角色
            SysRole sysRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
            MemberSysRole memberSysRole = new MemberSysRole(memberId, sysRole.getId());
            memberSysRoleService.insert(memberSysRole);
            return memberGroup;
        } else {
            // 从数据库取出记录的值
            MemberGroup t = memberGroupService.get(memberGroup.getId());
            // 将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(memberGroup, t);

            String realname = memberGroup.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
                t.setCopyrightName(realname);
            }
            memberGroupService.update(t);
            return t;
        }
    }

    /**
     * 解绑合作渠道角色
     *
     * @param cosponsorId 用户id
     * @author yifeng
     * @date 14:26 2019/10/8
     **/
    public void unBindCosponsorRole(String cosponsorId) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        MemberGroup member = memberGroupService.get(cosponsorId);
        member.setIsCosponsor(YesNoStatus.NO.getCode());
        memberGroupService.update(member);

        boolean hasRole = sysRoleService.hasRole(member.getId(), sysRole.getCode());
        if (hasRole) {
            memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), cosponsorId);
        }
    }

    /**
     * 获取行知公社用户id
     *
     * @return 行知公社用户id
     * @author yifeng
     * @date 10:08 2019/11/13
     **/
    public String getXzgsMemberId() {
        String memberId = "";
        // 获取行知公社参数配置
        SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
        if (xzgsConfig == null) {
            //正式环境中行知公社机构ID
            memberId = "c94e89415d7d4611b706cecfc43af2ae";
        } else {
            memberId = xzgsConfig.getValue();
        }
        return memberId;
    }
    /**
     * 检查账号信息是否存在
     *
     * @param memberGroup 用户信息
     * @return
     * @author yifeng
     * @date 10:44 2019/9/26
     **/
    public String checkAccountInfo(MemberGroup memberGroup) throws Exception {
        List<MemberGroup> mobile = memberGroupService.checkUserName("username", memberGroup.getUsername(),
                memberGroup.getId(), Constant.MEMBER_ORGANIZATION);
        if (mobile != null && mobile.size() > 0) {
            throw new Exception("登录名已存在");
        }

        String oldMemberId = null;
        if (StringUtils.isNotEmpty(memberGroup.getMobile())) {
            mobile = memberGroupService.checkUserName("mobile", memberGroup.getMobile(), memberGroup.getId(), Constant.MEMBER_ORGANIZATION);
            if (mobile != null && mobile.size() > 0) {
                if (mobile.size() == 1) {
                    if (StringUtils.isNotEmpty(memberGroup.getId()) && !memberGroup.getId().equals(mobile.get(0).getId())) {
                        throw new Exception("手机号已存在");
                    }
                    boolean hasPartner = sysRoleService.hasRole(mobile.get(0).getId(), RoleEnum.PARTNER_ROLE.getCode());
                    if (hasPartner) {
                        throw new Exception("手机号已存在");
                    } else {
                        oldMemberId = mobile.get(0).getId();
                    }
                } else {
                    throw new Exception("手机号已存在");
                }
            }
        }
        return oldMemberId;
    }

    /**
     * 设置合作商
     *
     * @param memberId 用户id
     * @author yifeng
     * @date 16:53 2019/10/8
     **/
    public void addPartner(String memberId, boolean isOneLevel) {
        MemberGroup member = memberGroupService.get(memberId);
        if (!YesNoStatus.YES.getCode().equals(member.getIsPartner())) {
            member.setIsPartner(1);
            memberGroupService.update(member);
        }

        SysRole partnerRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
        memberSysRoleService.getSet(memberId, partnerRole.getId());

        if (isOneLevel) {
            SysRole oneLevelChildRole = sysRoleService.getRole(RoleEnum.ONE_LEVEL_CHILD.getCode(), RoleType.SYSTEM_ROLE.getCode());
            memberSysRoleService.getSet(memberId, oneLevelChildRole.getId());
        }
    }

    /**
     * 添加行知公社角色
     *
     * @param childId 用户id
     * @author yifeng
     * @date 17:03 2019/10/8
     **/
    public void addXzgs(String childId) {
        boolean hasRole = sysRoleService.hasRole(childId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
        if (!hasRole) {
            SysRole partnerRole = sysRoleService.getRole(RoleEnum.KNOWING_COMMUNE_ROLE.getCode(), RoleType.PARTNER_ROLE.getCode());
            MemberSysRole memberSysRole = new MemberSysRole();
            memberSysRole.setMemberId(childId);
            memberSysRole.setRoleId(partnerRole.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    public CurrentUser turnIntoCurrentUser(MemberGroup member) {

        boolean hasXzgsAdmin = sysRoleService.hasRole(member.getId(), RoleEnum.XZGS_ADMIN.getCode());

        boolean isChild = memberGroupService.isChild(member.getId());
        CurrentUser currentUser = new CurrentUser();
        try {
            MyBeanUtils.copyBeanNotNull2Bean(member, currentUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        currentUser.setChild(isChild);

        if (hasXzgsAdmin) {
            currentUser.setXzgsAdmin(true);
        }

        if (isChild) {
            // 是否为一级子账号
            boolean hasOneLevelRole = sysRoleService.hasRole(member.getId(), RoleEnum.ONE_LEVEL_CHILD.getCode());
            currentUser.setOneLevelChildren(hasOneLevelRole);

            // 是否为二级子账号
            boolean hasTwoLevelRole = sysRoleService.hasRole(member.getPartnerId(), RoleEnum.ONE_LEVEL_CHILD.getCode());
            currentUser.setTwoLevelChildren(hasTwoLevelRole);
        } else {
            currentUser.setOneLevelChildren(false);
            currentUser.setTwoLevelChildren(false);
        }
        return currentUser;
    }
    /**
     * @Description: 获取分社小程序邀请二维码
     * @Param: [pmId]
     * @return: String
     * @Author: Hua Qunhao
     * @Date: 2020/06/16
     */
    public String getChildInviteQrCode(String partnerId) throws Exception {
        WechatOpenMember openMember = wechatOpenMemberService.
                findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_INTEGRAL);
        XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
        qrCodeRequest.setPage("pages/offline_invita/index");
        qrCodeRequest.setScene(partnerId);
        String filePath = fileBizService.getUploadCIPath(partnerId, "integralPartnerRecommend");
        String result = fileBizService.uploadCloudOutXcs(partnerId, filePath, qrCodeRequest,
                openMember.getAuthorizerAccessToken(), 1);
        return  result;
    }
}
